package com.itheima.health.util;

import com.itheima.health.pojo.OrderSetting;
import lombok.extern.slf4j.Slf4j;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.InputStream;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

@Slf4j
public class ExcelUtils {
    /**
     * 将excel文件中的数据解析
     * @param inputStream 传入的数据流
     * @return 解析结果
     */
    public static List<OrderSetting> excelToShopIdList(InputStream inputStream) {
        List<OrderSetting> dataList = new ArrayList<>();

        try (Workbook workbook = new XSSFWorkbook(inputStream)) {
            // 获取第一个工作表
            Sheet sheet = workbook.getSheetAt(0);
            // 从第二行遍历  getLastRowNum()获取到最后一行的第一列的数据作为结束条件
            for (int i = 1; i <= sheet.getLastRowNum(); i++) {
                Row row = sheet.getRow(i); // 获取当前行对象
                if (row != null) {
                    Cell dateCell = row.getCell(0); // 获取日期列
                    Cell quantityCell = row.getCell(1); // 获取号码列

                    if (dateCell != null && quantityCell != null) { // 解析单元格
                        Date date = DateUtil.getJavaDate(dateCell.getNumericCellValue());// 日期列
                        log.info("日期 ： {} ", date);
                        double quantity = quantityCell.getNumericCellValue(); // 可预约数量列

                        OrderSetting orderSetting = new OrderSetting();
                        orderSetting.setOrderDate(date);
                        orderSetting.setNumber((int) quantity);
                        orderSetting.setReservations(0);
                        dataList.add(orderSetting); // 将对象存入集合
                    }
                }
            }
        } catch (Exception e) {
            log.error("文件解析异常 : {}", e.toString());
            throw new RuntimeException(e);
        }

        return dataList;
    }
}
